<script setup lang="ts">
import { reactive, ref } from "vue";
import { userLoginType } from "@/types/user";
import type { FormInstance, FormRules } from "element-plus";
import { useUserStore } from "@/store/modules/user";
import { login } from "@/api/login"; //登录方法
const formData = reactive<userLoginType>({
  username: "",
  password: "",
});
const rules = reactive<FormRules>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名为3-20位数", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 3, max: 20, message: "请输入3-20位密码", trigger: "blur" },
  ],
});
const ruleFormRef = ref<FormInstance>();
const emits = defineEmits(["handleLogin"]);

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  await formEl.validate((valid, fields) => {
    if (!valid) return;
    login(formData)
      .then((res) => {
        emits("handleLogin", res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  });
};
</script>
<template>
  <div class="login-content">
    <div class="login-content-title">后台登录</div>
    <el-form
      size="large"
      label-position="top"
      :rules="rules"
      ref="ruleFormRef"
      :model="formData"
    >
      <el-form-item label="账号" prop="username">
        <el-input size="large" v-model="formData.username" placeholder="请输入账号" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          size="large"
          show-password
          v-model="formData.password"
          placeholder="请输入密码"
        />
      </el-form-item>
      <el-button type="primary" style="width: 100%" @click="submitForm(ruleFormRef)"
        >登录</el-button
      >
      <div class="login-bottom"></div>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.login-content {
  width: 100%;

  padding: 60px 40px;

  &-title {
    font-size: 24px;
    font-weight: 300;
    margin-bottom: 30px;
    text-align: center;
  }
}
.login-bottom {
  display: flex;
  margin-top: 20px;
  &-left {
    flex: 1;
  }
}
</style>
